//
//  JiaMiObject.m
//  IDPhoto
//
//  Created by njsx on 2022/5/23.
//  Copyright © 2022 Awei. All rights reserved.
//

#import "JiaMiObject.h"
#import "HMACSHA1.h"
@implementation JiaMiObject

+ (void)post:(NSString *)url params:(id)params success:(void (^)(NSDictionary *JSON))success failure:(void (^)(NSError * error))failure{
    NSString *time = [self haveShiJianChuo];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [request setTimeoutInterval:10.0];
    // 设置请求方法
    [request setHTTPMethod:@"POST"];
    [request addValue:[self bdaParamsDic:params timeStr:time] forHTTPHeaderField:@"Authorization"];
    [request addValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"bda.tencentcloudapi.com" forHTTPHeaderField:@"Host"];
    [request addValue:@"SegmentPortraitPic" forHTTPHeaderField:@"X-TC-Action"];
    [request addValue:time forHTTPHeaderField:@"X-TC-Timestamp"];
    [request addValue:@"2020-03-24" forHTTPHeaderField:@"X-TC-Version"];
    [request addValue:@"ap-beijing" forHTTPHeaderField:@"X-TC-Region"];
    NSError *error;
    NSData *postData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
    NSString *jsonString;
    jsonString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", jsonString);
    [request setHTTPBody: postData];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * data,NSURLResponse *response,NSError *error){
        if (error!=nil) {
            NSLog(@"错误");
            failure(error);
        }else{
            // 如果请求成功，则解析数据。
            id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
            if (error) {
                NSLog(@"post error :%@",error.localizedDescription);
                failure(error);
            }else {
                success(object);
            }
        }
    }];
    [task resume];
}
+(NSString *)bdaParamsDic:(NSDictionary *)params timeStr:(NSString *)time{
    NSString *SECRET_ID = @"AKID84oKcgV6SZR4SaT9duxmLehW5ORESQ8Z";
    NSString *SECRET_KEY = @"CCzWjgOq2ye4FBrHRL0VgW7SbQ0RccPz";
    NSString *service = @"bda";
    NSString *host = @"bda.tencentcloudapi.com";
    NSString *hostn = [host stringByAppendingString:@"\n"];
    NSString *algorithm = @"TC3-HMAC-SHA256";
    NSString *timestamp = time;
    NSString *date = [self newDate];
    NSString *httpRequestMethod = @"POST";
    NSString *canonicalUri = @"/";
    NSString *canonicalQueryString = @"";
    NSString *canonicalHeaders = [@"content-type:application/json; charset=utf-8\nhost:" stringByAppendingString:hostn];
    NSString *signedHeaders = @"content-type;host";
    NSDictionary *payloadDic = params;
    NSData *data1 = [NSJSONSerialization dataWithJSONObject:payloadDic options:0 error:nil];
    NSString *payloadJson = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
    NSString *hashedRequestPayload = [HMACSHA1 shaHas:payloadJson];
    NSString *canonicalRequest= [[NSString alloc] initWithFormat:@"%@%@%@%@%@%@%@%@%@%@%@", httpRequestMethod,@"\n",canonicalUri,@"\n", canonicalQueryString,@"\n", canonicalHeaders,@"\n", signedHeaders,@"\n", hashedRequestPayload];
    NSLog(@"canonicalRequest:%@",canonicalRequest);
    NSString *credentialScope = [[NSString alloc]initWithFormat: @"%@%@%@%@", date,@"/",service,@"/tc3_request"];
    NSString *hashedCanonicalRequest = [HMACSHA1 shaHas:canonicalRequest];
    NSLog(@"hashedCanonicalRequest:%@",hashedCanonicalRequest);
    NSString *stringToSign = [[NSString alloc] initWithFormat:@"%@%@%@%@%@%@%@", algorithm,@"\n",timestamp,@"\n",credentialScope,@"\n",hashedCanonicalRequest];
    NSString * key1 = [self hexStringFromString:[@"TC3" stringByAppendingString:SECRET_KEY]];
    NSString *secretDate = [HMACSHA1 hmacsha1:key1 key:date];
    NSString *secretService = [HMACSHA1 hmacsha1:secretDate key:service];
    NSString *secretSigning = [HMACSHA1 hmacsha1:secretService key:@"tc3_request"];
    NSString *signature = [HMACSHA1 hmacsha1:secretSigning key:stringToSign];
    NSString *authorization = [[NSString alloc] initWithFormat: @"%@ Credential=%@/%@, SignedHeaders=%@, Signature=%@",algorithm,SECRET_ID,credentialScope, signedHeaders, signature];
    return authorization;
}
+(NSString *)haveShiJianChuo {
    double currentTime =  [[NSDate date] timeIntervalSince1970];
    NSString *strTime = [NSString stringWithFormat:@"%.0f",currentTime];
    return strTime;
    
}
+(NSString *)newDate{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *str = [formatter stringFromDate:date];
    return str;
}
+ (NSString *)hexStringFromString:(NSString *)string{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        if([newHexStr length]==1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;
}
@end
